from re import compile
from urllib2 import urlopen
from json import loads

class YoukuFlvc:
    def __init__(self, url):
        self.ntitle = None
        self.nurl = None
        self.__parse(url)
            
    def __parse(self, url):
        urlpattern = compile(r"<a href *= *\"(http://k\.youku\.com/player/getFlvPath/[^\"]+)")
        fnpattern = compile(r'name=\"filename\" value=\"(.*)\"')
        typepattern = compile(r'<a href *= *\"http://k\.youku\.com/player/getFlvPath/[^\"]+/st/(mp4|flv)')
        flvcdurl = "http://www.flvcd.com/parse.php?kw=" + url + "&format=super"
        
        iid = compile(r'(http://|)v.youku.com/v_show/id_([a-zA-Z0-9]+).html').findall(url)[0][1]
        idUrl = 'http://v.youku.com/player/getPlayList/VideoIDS/' + iid
        
        response = urlopen(flvcdurl)
        data = response.read()
        self.segurls = urlpattern.findall(data)
        self.filename = fnpattern.findall(data)[0] + '.' + typepattern.findall(data)[0]

        
        try:
            meta_next = loads(urlopen(idUrl).read())['data'][0]['list_next']
            self.ntitle = meta_next['title']
            self.nurl = 'http://v.youku.com/v_show/id_' + meta_next['vidEncoded'] + '.html' 
        except:
            pass

if __name__ == '__main__':
    from downloader import Downloader        
    url = 'http://v.youku.com/v_show/id_XMjI2ODA3OTg4.html'
    while url:        
        youku = YoukuFlvc(url)
        downloader = Downloader(youku.filename, youku.segurls)
        downloader.download()
        
        if not youku.ntitle:
            print 'There is no next video, exit.'
            break
                
        ans = 'x'
        while ans not in ['Y','y','N','n']:
            print '========================================================================'
            print 'The next video is', youku.ntitle, ', Download it [y/n]:'
            ans = raw_input()
        if ans == 'N': break
        if ans == 'n': break
        url = youku.nurl
            
    
            